#include "FSM_Lite_Pro.h"

// 控制结构体
static FSM_TypeDef FSM_Control[FSM_Max_TaskID];

void FSM_Task_Init(FSM_TaskID id, fsm_func func)
{
    FSM_Control[id].Status = 0;
    FSM_Control[id].nTicks = 0;
    FSM_Control[id].Run = 0;

    if (func)
    {
        FSM_Control[id].func = func;
    }
}

void FSM_Task_Start(FSM_TaskID id, fsm_sta_t evt, fsm_time_t tick)
{
    FSM_Control[id].Event  = evt;
    FSM_Control[id].nTicks = tick;

    if (FSM_Control[id].nTicks == 0)
    {
        FSM_Control[id].Status |= evt;
        FSM_Control[id].Run = 1;
    }
}

void FSM_Task_Stop(FSM_TaskID id)
{
    FSM_Control[id].nTicks = 0;
    FSM_Control[id].Run = 0;
}

fsm_sta_t FSM_Evt_Set(FSM_TaskID id, fsm_sta_t evt)
{
    return FSM_Control[id].Status |= evt;
}

fsm_sta_t FSM_Evt_Clr(FSM_TaskID id, fsm_sta_t evt)
{
    return FSM_Control[id].Status &= ~evt;
}

fsm_sta_t *FSM_GetSta(FSM_TaskID id)
{
    return &FSM_Control[id].Status;
}

void FSM_Task_Run(void)
{
    FSM_TaskID i = FSM_Sys_TaskID;
    
    for (i = FSM_Sys_TaskID; i < FSM_Max_TaskID; i ++)
    {
        if (FSM_Control[i].Run)
        {
            FSM_Control[i].Run = FSM_Control[i].func(i);
        }
    }
}

void FSM_Timer_Run(void)
{
    FSM_TaskID i = FSM_Sys_TaskID;

    for (i = FSM_Sys_TaskID; i < FSM_Max_TaskID; i ++)
    {
        if (FSM_Control[i].nTicks)
        {
            FSM_Control[i].nTicks --;
            if (FSM_Control[i].nTicks == 0)
            {
                FSM_Control[i].Status |= FSM_Control[i].Event;
                FSM_Control[i].Run = 1;
            }
        }
    }
}
